package com.webdev.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.webdev.base.mapper.OrderMapper;
import com.webdev.base.pojo.Goods;
import com.webdev.base.pojo.Orders;
import com.webdev.base.pojo.User;
import com.webdev.base.service.IGoodsService;
import com.webdev.base.service.IOrderService;
import com.webdev.base.util.Constants;
import com.webdev.base.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author huangningshuang
 * @since 2021-12-13
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 下单操作: 减库存，存订单，同步redis中订单
     *
     * @param user
     * @param goodsVo
     */
    @Override
    public void secKill(User user, GoodsVo goodsVo) {
        //当库存大于0，id等于商品id的时候，将当前库存数量存入数据库
        goodsService.update(new UpdateWrapper<Goods>()
                .setSql("goods_count = goods_count-1").eq("goods_id", goodsVo.getGoodsId()).gt("goods_count", 0));

        Orders order = new Orders();
        order.setOrderUid(user.getUserId());
        order.setOrderGoodsId(goodsVo.getGoodsId());
        orderMapper.insertOrder(order);

        //更新redis缓存
        redisTemplate.opsForValue().set(Constants.REDIS_ORDERKEY + user.getUserId(), order);
        redisTemplate.delete(Constants.REDIS_HANDLINGUSER + user.getUserId());
    }
}
